package com.rzico.order.controller;


import com.rzico.account.service.PaymentService;
import com.rzico.annotation.Log;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.plugin.RiderPlugin;
import com.rzico.core.plugin.dada.DadaDeliverPlugin;
import com.rzico.core.rider.RiderApiResponse;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 配送
 *
 * @author xz
 * @version 1.0
 * @date 2021-01-28
 */
@Api(description = "骑手回调")
@RestController
@RequestMapping("/rider")
public class RiderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    private SysSequenceService sysSequenceService;

    /**
     *  支付通知
     *
     * @param riderPluginId
     * @return
     */
    @Log(desc = "支付通知", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("支付通知")
    @PostMapping("/notify/{riderPluginId}/{mchId}")
    public void notify(@PathVariable String riderPluginId, @PathVariable String mchId, HttpServletRequest request, HttpServletResponse response) {

        RiderPlugin riderPlugin = sysPluginService.getRiderPlugin(riderPluginId);

        SysPlugin sysPlugin = sysPluginService.findByPlugin(mchId,riderPluginId);

        RiderApiResponse riderApiResponse = riderPlugin.verifyNotify(sysPlugin,request);

        String notifyMessage = "error";
        if (riderApiResponse.getCode()==0) {
            //此处改为MQ通知异步执行
            try {
                String sn = null;
                if (5==riderApiResponse.getStatusCode() || 7==riderApiResponse.getStatusCode()) {
                    sn = sysSequenceService.generate("refunds");
                }
                orderService.riderNotify(riderApiResponse,sn);
                notifyMessage = riderPlugin.getNotifyMessage(request);
            } catch (Exception e) {
                notifyMessage = "error";
            }

        }
        try {
            PrintWriter out = response.getWriter();
            out.print(notifyMessage);
            out.flush();
        } catch (IOException e) {

        }

    }

}
